import { postProfitSharing } from "../../utils/wx/wxpay";
import { api } from "./api";

// const spMchId = process.env.WX_SP_MCHID;

export async function postShareProfit(sid = 0) {
  const shop = await api.getShopRow(sid);
  if (!shop) {
    throw "no shop";
  }
  if (!shop.mch_id || !shop.share_rate) {
    throw "未设置分成信息";
  }
  const ordList = await api.getOrderList(
    {
      sid,
      // _limit: 10,
      // shared: 2,
    },
    "/data/list/order_share"
  );
  for (const row of ordList) {
    try {
      const { pay_info } = row;
      const amount = Math.floor((pay_info.payer_total * shop.share_rate) / 100);
      const data = await postProfitSharing({
        transaction_id: pay_info.trans_id,
        out_order_no: row.order_no,
        sub_mchid: shop.mch_id,
        receivers: [
          {
            type: "PERSONAL_OPENID",
            account: "ojIoZ7Tf5Agyx6IOp-39eEHmfmtQ",
            amount,
            description: `分账${shop.share_rate}%给服务商`,
          },
        ],
      });
      // console.log(data);
      Object.assign(pay_info, {
        share_info: {
          amount,
          rate: shop.share_rate,
          oid: data.order_id,
        },
      });
      await api.postOrder({
        id: row.id,
        shared: 1,
        pay_info,
      });
    } catch (error) {
      console.log(error);
      api.postOrder({
        id: row.id,
        shared: 2,
      });
      row.shared = 2;
    }
  }
  return ordList;
}
